/**
 * menkor.com Inc.
 * Copyright (c) 2012-2019 All Rights Reserved.
 */
package com.blueskykong.concurrency.lock;

import java.util.Date;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author keets
 * @date 2019-10-08.
 */
public class DeadLock {
    public static String obj1 = "obj1";
    public static String obj2 = "obj2";
    final Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        LockA la = new LockA();
        new Thread(la).start();
        LockB lb = new LockB();
        new Thread(lb).start();
    }

    static class LockA implements Runnable {
        public void run() {
            try {
                System.out.println(new Date().toString() + " LockA 开始执行");
                while (true) {
                    synchronized (DeadLock.obj1) {
                        System.out.println(new Date().toString() + " LockA 锁住 obj1");
                        Thread.sleep(1000); // 此处等待是给B能锁住机会
                        synchronized (DeadLock.obj2) {
                            System.out.println(new Date().toString() + " LockA 锁住 obj2");
//                        Thread.sleep(60 * 1000); // 为测试，占用了就不放
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    static class LockB implements Runnable {
        public void run() {
            try {
                System.out.println(new Date().toString() + " LockB 开始执行");
                while (true) {
                    synchronized (DeadLock.obj2) {
                        System.out.println(new Date().toString() + " LockB 锁住 obj2");
                        Thread.sleep(1000); // 此处等待是给A能锁住机会
                        synchronized (DeadLock.obj1) {
                            System.out.println(new Date().toString() + " LockB 锁住 obj1");
//                        Thread.sleep(60 * 1000); // 为测试，占用了就不放
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
